package com.iot.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iot.core.*;
import com.iot.pojo.MTmenu;
import com.iot.service.TmenuService;
import com.iot.util.Common;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/system/menu/")
public class TMenuController extends BaseController {

    @Autowired
    private TmenuService service;
    @ResponseBody
    @RequestMapping("save")

    public LResult save(@RequestParam String bean) {
        try {
          //  String menu = request.getParameter("menu");
            MTmenu entity = JsonHelper.toBean(bean, MTmenu.class);
            int id = 0;
            if (entity.getMENU_ID() > 0) {
                service.update(entity);
            } else {
                id = service.insert(entity);

            }
            return LResult.Success(entity.getMENU_ID());
        } catch (Exception ex) {
            return LResult.Error(ex.getMessage());
        }
    }


    @ResponseBody
    @RequestMapping("get")
    public String getByid(@RequestParam Integer id) {
        try {
            //  String menu = request.getParameter("menu");
            MTmenu bean = service.single(id);
            return LResult.Success(bean).toJson();
        } catch (Exception ex) {
            return LResult.Error(ex.getMessage()).toJson();
        }
    }

    @ResponseBody
    @RequestMapping("del")
    public String deleteByid(@RequestParam Integer id) {
        try {
            //  String menu = request.getParameter("menu");
            service.deleteById(id);
            return LResult.Success().toJson();
        } catch (Exception ex) {
            return LResult.Error(ex.getMessage()).toJson();
        }
    }

    @ResponseBody
    @RequestMapping("query")
    public String queryByPage() {

        try {
            //" AND SNAME LIKE '" + key + "%'"
            //   Map map = request.getParameterMap(); // 获取所有参数
            PageData map = getPageData();
            if (!map.containsKey("keyword")) {
                map.put("keyword", "");
            }
            if (!map.containsKey("sname")) {
                map.put("sname", "");
            }

            PageHelper.startPage(Common.toInt(map.get("page")), Common.toInt(map.get("limit")));
            List<MTmenu> list = service.fetchByPage(map);
            PageInfo<MTmenu> pageInfo = new PageInfo<>(list);
            return LResult.Success((int)pageInfo.getTotal(),pageInfo.getList()).toJson();
        } catch (Exception ex) {
            return  LResult.Error("数据错误").toJson();
        }
    }
}
